package leetcode.binaryTree;

import utils.printer.BinaryTrees;
import datastructure.tree.BinarySearchTree;
import datastructure.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Description: https://leetcode.cn/problems/binary-tree-preorder-traversal/
 * 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。
 * @Author Ammar
 * @Create 2023/3/29 17:18
 */
public class _144_二叉树的前序遍历 {
    public static List<Integer> preorderTraversal(TreeNode<Integer> root) {
        List<Integer> datas = new ArrayList<>();
        if (root == null) return datas;
        datas.add(root.val);

        datas.addAll(preorderTraversal(root.left));
        datas.addAll(preorderTraversal(root.right));
        return datas;
    }


    /**
     * 思路：前序遍历，非递归，使用栈
     * 将全部 node = node.left 添加到数组中，如果左节点有右节点，将右节点添加到栈中 stack.push(node.right)
     * if (node.left == null), node = stack.pop()，继续遍历
     * node = stack.pop()，实际上是将上一层的右节点赋值给 node = node.right
     * @param root
     * @return
     */
    public static List<Integer> preorderTraversal2(TreeNode<Integer> root) {
        List<Integer> datas = new ArrayList<>();
        if (root == null) return datas;
        Stack<TreeNode<Integer>> stack = new Stack<>();
        TreeNode<Integer> node = root;
        while (true) {
            if (node != null) {
                datas.add(node.val);
                if (node.right != null) {
                    stack.push(node.right);
                }
                node = node.left;
            } else if (stack.isEmpty()) {
                return datas;
            } else {
                node = stack.pop();
            }
        }
    }

    public static void main(String[] args) {
        Integer[] data = new Integer[]{
                7, 4, 9, 2, 5, 8 ,11, 3, 12, 1
        };
        BinarySearchTree<Integer> binarySearchTree = new BinarySearchTree<>();
        for (int i = 0; i < data.length; i++) {
            binarySearchTree.add(data[i]);
        }
        BinaryTrees.print(binarySearchTree);
        List<Integer> integers = preorderTraversal(binarySearchTree.getRoot());
        integers.forEach(System.out::println);
    }
}
